<template>
  <div class="dashboard">
    <div class="dashboard-header">
      <h1>仪表盘</h1>
      <p class="welcome-text">欢迎回来，{{ authStore.user?.username }}！</p>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stats-card stats-card-primary">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon><Reading /></el-icon>
            </div>
            <div class="stats-info">
              <h3>{{ stats.totalLessons }}</h3>
              <p>总课程数</p>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stats-card stats-card-success">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon><Folder /></el-icon>
            </div>
            <div class="stats-info">
              <h3>{{ stats.totalCategories }}</h3>
              <p>分类数量</p>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stats-card stats-card-warning">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon><PriceTag /></el-icon>
            </div>
            <div class="stats-info">
              <h3>{{ stats.totalTags }}</h3>
              <p>标签数量</p>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stats-card stats-card-info">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon><View /></el-icon>
            </div>
            <div class="stats-info">
              <h3>{{ formatNumber(stats.totalViews) }}</h3>
              <p>总浏览量</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表和数据 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :xs="24" :lg="16">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>最近课程</span>
              <el-button type="link" @click="$router.push('/admin/lessons')">
                查看全部
              </el-button>
            </div>
          </template>
          
          <el-table
            :data="recentLessons"
            style="width: 100%"
            v-loading="isLoading"
            empty-text="暂无数据"
          >
            <el-table-column prop="title" label="课程标题" min-width="200">
              <template #default="{ row }">
                <div class="lesson-title">
                  <span>{{ row.title }}</span>
                  <el-tag
                    v-if="row.isFeatured"
                    type="warning"
                    size="small"
                    class="featured-tag"
                  >
                    推荐
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            
            <el-table-column prop="category.name" label="分类" width="120" />
            
            <el-table-column prop="difficulty" label="难度" width="100">
              <template #default="{ row }">
                <el-tag
                  :type="getDifficultyType(row.difficulty)"
                  size="small"
                >
                  {{ getDifficultyText(row.difficulty) }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="viewCount" label="浏览量" width="100" />
            
            <el-table-column prop="isPublished" label="状态" width="100">
              <template #default="{ row }">
                <el-tag
                  :type="row.isPublished ? 'success' : 'info'"
                  size="small"
                >
                  {{ row.isPublished ? '已发布' : '草稿' }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button
                  type="text"
                  size="small"
                  @click="$router.push(`/admin/lessons/${row.id}/edit`)"
                >
                  编辑
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :lg="8">
        <el-card class="quick-actions-card">
          <template #header>
            <span>快速操作</span>
          </template>
          
          <div class="quick-actions">
            <el-button
              type="primary"
              :icon="Plus"
              class="action-btn"
              @click="$router.push('/admin/lessons/create')"
            >
              创建课程
            </el-button>
            
            <el-button
              type="success"
              :icon="FolderAdd"
              class="action-btn"
              @click="showCategoryDialog = true"
            >
              添加分类
            </el-button>
            
            <el-button
              type="warning"
              :icon="PriceTag"
              class="action-btn"
              @click="showTagDialog = true"
            >
              添加标签
            </el-button>
            
            <el-button
              type="info"
              :icon="UploadFilled"
              class="action-btn"
              @click="$router.push('/admin/files')"
            >
              文件管理
            </el-button>
          </div>
        </el-card>
        
        <!-- 系统信息 -->
        <el-card class="system-info-card">
          <template #header>
            <span>系统信息</span>
          </template>
          
          <div class="system-info">
            <div class="info-item">
              <span class="label">当前版本：</span>
              <span class="value">v1.0.0</span>
            </div>
            <div class="info-item">
              <span class="label">最后登录：</span>
              <span class="value">{{ formatTime(authStore.user?.lastLoginAt) }}</span>
            </div>
            <div class="info-item">
              <span class="label">系统状态：</span>
              <el-tag type="success" size="small">正常运行</el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 快速添加分类对话框 -->
    <el-dialog
      v-model="showCategoryDialog"
      title="添加分类"
      width="400px"
      :before-close="closeCategoryDialog"
    >
      <el-form
        ref="categoryFormRef"
        :model="categoryForm"
        :rules="categoryRules"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="标识" prop="slug">
          <el-input v-model="categoryForm.slug" placeholder="请输入分类标识" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="categoryForm.description"
            type="textarea"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="closeCategoryDialog">取消</el-button>
        <el-button type="primary" @click="handleCreateCategory">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 快速添加标签对话框 -->
    <el-dialog
      v-model="showTagDialog"
      title="添加标签"
      width="400px"
      :before-close="closeTagDialog"
    >
      <el-form
        ref="tagFormRef"
        :model="tagForm"
        :rules="tagRules"
        label-width="80px"
      >
        <el-form-item label="标签名称" prop="name">
          <el-input v-model="tagForm.name" placeholder="请输入标签名称" />
        </el-form-item>
        <el-form-item label="标识" prop="slug">
          <el-input v-model="tagForm.slug" placeholder="请输入标签标识" />
        </el-form-item>
        <el-form-item label="颜色">
          <el-color-picker v-model="tagForm.color" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="closeTagDialog">取消</el-button>
        <el-button type="primary" @click="handleCreateTag">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useLessonStore } from '@/stores/lesson'
import { useCategoryStore } from '@/stores/category'
import {
  Reading,
  Folder,
  PriceTag,
  View,
  Plus,
  FolderAdd,
  UploadFilled
} from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'

const router = useRouter()
const authStore = useAuthStore()
const lessonStore = useLessonStore()
const categoryStore = useCategoryStore()

const isLoading = ref(false)
const showCategoryDialog = ref(false)
const showTagDialog = ref(false)

// 统计数据
const stats = reactive({
  totalLessons: 0,
  totalCategories: 0,
  totalTags: 0,
  totalViews: 0
})

// 最近课程列表
const recentLessons = computed(() => lessonStore.recentLessons.slice(0, 5))

// 分类表单
const categoryFormRef = ref<FormInstance>()
const categoryForm = reactive({
  name: '',
  slug: '',
  description: ''
})

const categoryRules: FormRules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  slug: [{ required: true, message: '请输入分类标识', trigger: 'blur' }]
}

// 标签表单
const tagFormRef = ref<FormInstance>()
const tagForm = reactive({
  name: '',
  slug: '',
  color: '#409EFF'
})

const tagRules: FormRules = {
  name: [{ required: true, message: '请输入标签名称', trigger: 'blur' }],
  slug: [{ required: true, message: '请输入标签标识', trigger: 'blur' }]
}

// 格式化数字
const formatNumber = (num: number) => {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + 'w'
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'k'
  }
  return num.toString()
}

// 格式化时间
const formatTime = (time?: string) => {
  if (!time) return '无'
  return new Date(time).toLocaleString('zh-CN')
}

// 获取难度类型
const getDifficultyType = (difficulty: string) => {
  const types: Record<string, string> = {
    beginner: 'success',
    intermediate: 'warning',
    advanced: 'danger'
  }
  return types[difficulty] || 'info'
}

// 获取难度文本
const getDifficultyText = (difficulty: string) => {
  const texts: Record<string, string> = {
    beginner: '初级',
    intermediate: '中级',
    advanced: '高级'
  }
  return texts[difficulty] || difficulty
}

// 关闭分类对话框
const closeCategoryDialog = () => {
  showCategoryDialog.value = false
  categoryFormRef.value?.resetFields()
}

// 关闭标签对话框
const closeTagDialog = () => {
  showTagDialog.value = false
  tagFormRef.value?.resetFields()
}

// 创建分类
const handleCreateCategory = async () => {
  if (!categoryFormRef.value) return

  try {
    await categoryFormRef.value.validate()
    await categoryStore.createCategory({
      ...categoryForm,
      isActive: true,
      sortOrder: 0
    })
    closeCategoryDialog()
    loadStats()
  } catch (error) {
    console.error('创建分类失败:', error)
  }
}

// 创建标签
const handleCreateTag = async () => {
  if (!tagFormRef.value) return

  try {
    await tagFormRef.value.validate()
    // 这里需要创建标签的store方法，暂时用模拟
    console.log('创建标签:', tagForm)
    closeTagDialog()
    loadStats()
  } catch (error) {
    console.error('创建标签失败:', error)
  }
}

// 加载统计数据
const loadStats = async () => {
  try {
    // 模拟统计数据
    stats.totalLessons = 45
    stats.totalCategories = 8
    stats.totalTags = 23
    stats.totalViews = 125680
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 加载最近课程
const loadRecentLessons = async () => {
  try {
    isLoading.value = true
    await lessonStore.fetchRecentLessons(5)
  } catch (error) {
    console.error('加载最近课程失败:', error)
  } finally {
    isLoading.value = false
  }
}

onMounted(async () => {
  await Promise.all([
    loadStats(),
    loadRecentLessons()
  ])
})
</script>

<style scoped>
.dashboard {
  padding: 0;
}

.dashboard-header {
  margin-bottom: 24px;
}

.dashboard-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.welcome-text {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.stats-row {
  margin-bottom: 24px;
}

.stats-card {
  margin-bottom: 16px;
  border: none;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stats-card-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.stats-card-success {
  background: linear-gradient(135deg, #2ecc71 0%, #27ae60 100%);
  color: white;
}

.stats-card-warning {
  background: linear-gradient(135deg, #f39c12 0%, #e67e22 100%);
  color: white;
}

.stats-card-info {
  background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
  color: white;
}

.stats-card :deep(.el-card__body) {
  padding: 20px;
}

.stats-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stats-icon {
  font-size: 40px;
  opacity: 0.8;
}

.stats-info h3 {
  margin: 0 0 4px 0;
  font-size: 32px;
  font-weight: bold;
}

.stats-info p {
  margin: 0;
  font-size: 14px;
  opacity: 0.9;
}

.chart-row {
  margin-bottom: 24px;
}

.chart-card,
.quick-actions-card,
.system-info-card {
  margin-bottom: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.lesson-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.featured-tag {
  font-size: 12px;
}

.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.action-btn {
  width: 100%;
  height: 48px;
  border-radius: 8px;
  justify-content: flex-start;
}

.system-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  color: #909399;
  font-size: 14px;
}

.value {
  color: #303133;
  font-size: 14px;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-row {
    margin-bottom: 16px;
  }
  
  .stats-card {
    margin-bottom: 12px;
  }
  
  .stats-content {
    flex-direction: column;
    text-align: center;
    gap: 8px;
  }
  
  .stats-icon {
    font-size: 32px;
  }
  
  .stats-info h3 {
    font-size: 24px;
  }
}
</style> 